package com.zkthink.ceres.applet.order.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.deserializer.AbstractDateDeserializer;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.binarywang.wxpay.bean.order.WxPayAppOrderResult;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
import com.wechat.pay.java.service.payments.jsapi.model.Amount;
import com.wechat.pay.java.service.payments.jsapi.model.Payer;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayRequest;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayWithRequestPaymentResponse;
import com.zkthink.base.R;
import com.zkthink.ceres.applet.authority.domain.entity.AppletMember;
import com.zkthink.ceres.applet.authority.mapper.AppletMemberMapper;
import com.zkthink.ceres.applet.ceresStore.domain.entity.CeresStore;
import com.zkthink.ceres.applet.ceresStore.mapper.CeresStoreMapper;
import com.zkthink.ceres.applet.commission.domain.entry.AppletCommission;
import com.zkthink.ceres.applet.commission.mapper.AppletCommissionMapper;
import com.zkthink.ceres.applet.commission.service.AppletCommissionService;
import com.zkthink.ceres.applet.common.domin.PageDate;
import com.zkthink.ceres.applet.order.domain.entity.AppletProductOrder;
import com.zkthink.ceres.applet.order.domain.vo.*;
import com.zkthink.ceres.applet.order.mapper.AppletProductOrderMapper;
import com.zkthink.ceres.applet.order.service.AppletProductOrderService;
import com.zkthink.ceres.applet.pcVehicles.domain.entity.PcVehicles;
import com.zkthink.ceres.applet.pcVehicles.mapper.PcVehiclesMapper;
import com.zkthink.ceres.applet.propertyDetail.domain.entity.AppletPropertyDetail;
import com.zkthink.ceres.applet.referralrewards.domain.entry.Referralrewards;
import com.zkthink.ceres.applet.referralrewards.mapper.ReferralrewardsMapper;
import com.zkthink.ceres.applet.server.mapper.AppletStoreServerMapper;
import com.zkthink.ceres.applet.server.mapper.AppletVehiclesServerMapper;
import com.zkthink.ceres.common.utils.QcodeUtil;
import com.zkthink.ceres.file.properties.FileServerProperties;
import com.zkthink.ceres.member.entity.Member;
import com.zkthink.ceres.member.service.MemberService;
import com.zkthink.ceres.pay.service.PayService;
import com.zkthink.ceres.store.dao.StoreWithdrawHisMapper;
import com.zkthink.ceres.store.dto.HeXiaoDto;
import com.zkthink.ceres.store.entity.Store;
import com.zkthink.clh.order.vo.ChlPlaceOrderVO;
import com.zkthink.context.BaseContextHandler;
import com.zkthink.exception.BizException;
import com.zkthink.utils.StrPool;
import com.zkthink.zhl.order.dao.ChlOrderRefundMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zkthink.ceres.applet.order.mapper.AppletServerOrderMapper;
import com.zkthink.ceres.applet.order.domain.entity.AppletServerOrder;
import com.zkthink.ceres.applet.order.service.AppletServerOrderService;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static com.zkthink.ceres.applet.authority.config.AuthorityWebConfiguration.getMid;
import static com.zkthink.utils.DateUtils.DEFAULT_MONTH_FORMAT_SLASH;

/**
 * @Author cmz
 * @Date 2024-04-30 9:32
 */
@Service
public class AppletServerOrderServiceImpl extends ServiceImpl<AppletServerOrderMapper, AppletServerOrder> implements AppletServerOrderService {
    @Resource
    private AppletServerOrderMapper appletServerOrderMapper;

    @Resource
    private AppletMemberMapper appletMemberMapper;

    @Resource
    private PayService payService;

    @Resource
    private FileServerProperties fileProperties;

    @Resource
    private CeresStoreMapper ceresStoreMapper;

    @Resource
    private AppletProductOrderMapper appletProductOrderMapper;

    @Resource
    private MemberService memberService;
    @Resource
    private PcVehiclesMapper pcVehiclesMapper;

    @Value("${ceres.wx.app.appid}")
    private String appid;

    @Value("${ceres.wx.app.secret}")
    private String secret;

    @Autowired
    private RedisConnectionFactory j2CahceRedisConnectionFactory;
    @Autowired
    private AppletProductOrderService appletProductOrderService;
    @Resource
    private AppletCommissionService appletCommissionService;
    
    public static final String SERIAL_KEY = "SERIAL:NUMBER";

    public static RSAAutoCertificateConfig config = null ;
    public static JsapiServiceExtension service = null ;

    @Override
    public R placeServerOrder(PlaceServerOrderVo placeServerOrderVo) {
        System.out.println("购买参数:" + placeServerOrderVo.toString());
        Long mid = BaseContextHandler.getUserId();
        Member member = memberService.findById(mid);
        ChlPlaceOrderVO placeOrderVO = new ChlPlaceOrderVO();

        //余额支付
        if (placeServerOrderVo.getPayChannel() == 2) {
            BigDecimal add = new BigDecimal(0);
            if (member.getVipTime() == null || !member.getVipTime().isAfter(LocalDateTime.now())) {
                add = member.getBalance();
            } else {
                add = member.getBalance().add(member.getCoupons());
            }
            if (placeServerOrderVo.getCash().compareTo(add) > 0) {
                return R.fail("余额不足");
            }
        }
        if (placeServerOrderVo.getProductType().equals("服务分类")) {
            AppletServerOrder serverOrder = new AppletServerOrder();

            serverOrder.setMid(BaseContextHandler.getUserId());//用户
            if (placeServerOrderVo.getServerId() == null) {
                return R.fail("没有选择服务!!!");
            }
            serverOrder.setServerId(placeServerOrderVo.getServerId());//服务
            if (placeServerOrderVo.getPayChannel() == null) {
                return R.fail("没有选择支付方式!!!");
            }
            serverOrder.setPayChannel(placeServerOrderVo.getPayChannel());//支付方式
            serverOrder.setPayStatus(1);//支付状态
            //serverOrder.setServerChannel(placeServerOrderVo.getServerChannel());//服务方式
            serverOrder.setCosts(placeServerOrderVo.getCosts());
            serverOrder.setBookingTime(placeServerOrderVo.getBookingTime());//用户选择预约上门和到店的时间
            serverOrder.setOrderRamark(placeServerOrderVo.getOrderRamark());//备注
            //serverOrder.setServerStatus(1);//订单状态：1.待选择  等待用户选择
            String orderCode = next("", 32);
            serverOrder.setOrderCode(orderCode);
            placeOrderVO.setOrderCode(orderCode);
            String payNum = next("",32);
            serverOrder.setPayNum(payNum);
            serverOrder.setPaySum(placeServerOrderVo.getCash());
            serverOrder.setCoupons(placeServerOrderVo.getCoupons());
            serverOrder.setAddressId(placeServerOrderVo.getAddressId());
            serverOrder.setBookingTime(placeServerOrderVo.getBookingTime());
            serverOrder.setCreateTime(new Date());
            serverOrder.setIsDelete(0);
            serverOrder.setCreateUser(String.valueOf(getMid()));
            if (placeServerOrderVo.getDeliveryMethod() == null
                    || (placeServerOrderVo.getDeliveryMethod() != 0
                    && placeServerOrderVo.getDeliveryMethod() != 1)) {
                return R.fail("没有选择服务方式或传入的数据值错误!!!");
            }
            serverOrder.setServerChannel(placeServerOrderVo.getDeliveryMethod());
        /*if (setServerStoreOrVehiclesVo.getBookingTime()==null){
            return R.fail("没有指定预约时间!!!");
        }*/
            if (serverOrder.getServerChannel() == 0) {
                //上门
                if (placeServerOrderVo.getStoreId() == null) {
                    return R.fail("没有选择理疗车id!!!");
                }
                serverOrder.setVehiclesId(placeServerOrderVo.getStoreId());
                PcVehicles pcVehicles = pcVehiclesMapper.selectById(placeServerOrderVo.getStoreId());
                //serverOrder.setLicensePlate(pcVehicles.getLicensePlate());
                serverOrder.setAddressId(placeServerOrderVo.getAddressId());
                if (pcVehicles.getCommission()!=null) {
                    BigDecimal multiply = new BigDecimal(pcVehicles.getCommission()).multiply(serverOrder.getCosts()).divide(new BigDecimal(100));
                    serverOrder.setCutAmount(multiply);
                }
            }
            if (serverOrder.getServerChannel() == 1) {
                //到店
                if (placeServerOrderVo.getStoreId() == null) {
                    return R.fail("没有选择店铺!!!");
                }
                Store store = ceresStoreMapper.findById(placeServerOrderVo.getStoreId());
                store.setStoreName(store.getStoreName());
                serverOrder.setStoreId(placeServerOrderVo.getStoreId());
                if (store.getCommission()!=null) {
                    BigDecimal multiply = new BigDecimal(store.getCommission()).multiply(serverOrder.getCosts()).divide(new BigDecimal(100));
                    serverOrder.setCutAmount(multiply);
                }
            }
            serverOrder.setServerStatus(2);//设置订单状态为待确认
            
            
            //添加核销码
            serverOrder.setCodeUrl(qRCodeUrl(String.valueOf(serverOrder.getOrderCode())));

            int i = appletServerOrderMapper.insert(serverOrder);
            placeOrderVO.setOrderId(serverOrder.getId());


            //微信app
            if (placeServerOrderVo.getPayChannel() == 1) {
//                WxPayAppOrderResult result = wxPay2(orderCode, placeServerOrderVo.getCash(), null, placeServerOrderVo.getIp(), placeServerOrderVo.getOrderRamark());
//                if (result.getPackageValue() != null) {
//                    serverOrder.setPrepayId(JSON.toJSONString(result));
//                    appletServerOrderMapper.updateById(serverOrder);
//                }
//                else {
//                    serverOrder.setPayStatus(3);
//                    appletServerOrderMapper.updateById(serverOrder);
//                    return R.fail("下单失败");
//                }
//                placeOrderVO.setObject(result);
                //返回数据，前端调起支付
                PrepayWithRequestPaymentResponse payment = payment(orderCode,member.getOpenid(), placeServerOrderVo.getCash().multiply(new BigDecimal(100)));
                placeOrderVO.setObject(payment);
            }//余额支付
            else if (placeServerOrderVo.getPayChannel() == 2) {
                if (placeServerOrderVo.getCash().compareTo(member.getCoupons()) <= 0) {
                    member.setCoupons(member.getCoupons().subtract(placeServerOrderVo.getCash()));//使用的消费金支付？
                } else {
                    member.setCoupons(new BigDecimal(0));//消费金全部使用
                    member.setBalance(member.getBalance().subtract(placeServerOrderVo.getCash().subtract(member.getCoupons())));//余额减去不够付的付款金额
                }
                serverOrder.setPayTime(new Date());
                serverOrder.setPayStatus(2);
                memberService.updateById(member);
                appletServerOrderMapper.updateById(serverOrder);
                serverOrder.setCodeUrl(qRCodeUrl(serverOrder.getOrderCode()));
                placeOrderVO.setObject(orderCode);
            }
        }
        else if (placeServerOrderVo.getProductType().equals("产品分类")){
            AppletProductOrder appletProductOrder = new AppletProductOrder();
            appletProductOrder.setMid(mid);
            appletProductOrder.setProductId(placeServerOrderVo.getServerId());
            appletProductOrder.setDiseasesSuffered(placeServerOrderVo.getDiseasesSuffered());
            appletProductOrder.setIllnessTime(placeServerOrderVo.getIllnessTime());
            appletProductOrder.setPayChannel(placeServerOrderVo.getPayChannel());
            appletProductOrder.setPayStatus(1);//初始化设置支付状态为未支付
            appletProductOrder.setProductStatus(1);//初始化设置订单状态为待选择
            appletProductOrder.setCosts(placeServerOrderVo.getCosts());//设置产品价格
            appletProductOrder.setPaySum(placeServerOrderVo.getCash());//付款金额
            appletProductOrder.setCoupons(placeServerOrderVo.getCoupons());//消费金额
            appletProductOrder.setOrderCode(UUID.randomUUID().toString());
            appletProductOrder.setAddressId(placeServerOrderVo.getAddressId());

            String orderCode = next("", 32);
            appletProductOrder.setOrderCode(orderCode);
            placeOrderVO.setOrderCode(orderCode);
            String payNum = next("",32);
            appletProductOrder.setPayNum(payNum);
            appletProductOrder.setPaySum(placeServerOrderVo.getCash());
            appletProductOrder.setCoupons(placeServerOrderVo.getCoupons());
            appletProductOrder.setCreateTime(new Date());
            appletProductOrder.setIsDelete(0);
            appletProductOrder.setCreateUser(String.valueOf(getMid()));
            appletProductOrder.setDeliveryMethod(placeServerOrderVo.getDeliveryMethod());
            appletProductOrder.setCodeUrl(qRCodeUrl(appletProductOrder.getOrderCode()));
            if (placeServerOrderVo.getDeliveryMethod()==2){
                //门店取货
                appletProductOrder.setStoreId(placeServerOrderVo.getStoreId());
                Store store = ceresStoreMapper.findById(placeServerOrderVo.getStoreId());
                if (store.getCommission()!=null) {
                    BigDecimal multiply = new BigDecimal(store.getCommission()).multiply(appletProductOrder.getCosts()).divide(new BigDecimal(100));
                    appletProductOrder.setCutAmount(multiply);
                }
               // appletProductOrder.setStoreName(store.getStoreName());
            }else if (placeServerOrderVo.getDeliveryMethod()==1){
                //车辆取货
                appletProductOrder.setVehiclesId(placeServerOrderVo.getStoreId());
                PcVehicles pcVehicles = pcVehiclesMapper.selectById(placeServerOrderVo.getStoreId());
                //appletProductOrder.setLicensePlate(pcVehicles.getLicensePlate());
                if (pcVehicles.getCommission()!=null) {
                    BigDecimal multiply = new BigDecimal(pcVehicles.getCommission()).multiply(appletProductOrder.getCosts()).divide(new BigDecimal(100));
                    appletProductOrder.setCutAmount(multiply);
                }

            }else if(placeServerOrderVo.getDeliveryMethod()==0){
                //快递取货
                appletProductOrder.setStoreId(placeServerOrderVo.getStoreId());
                appletProductOrder.setAddressId(placeServerOrderVo.getAddressId());
                appletProductOrder.setCodeUrl(null);
            }else {
                return R.fail("取货方式填写错误");
            }
//            if (order.getProductStatus()!=1){
//                return R.fail("当前订单的状态未处于《待选择》，设置失败!!!");
//            }
            appletProductOrder.setProductStatus(2);

            //添加核销码

            int insert = appletProductOrderMapper.insert(appletProductOrder);
            placeOrderVO.setOrderId(appletProductOrder.getId());

            //微信app
            if (placeServerOrderVo.getPayChannel() == 1) {
//                WxPayAppOrderResult result = wxPay2(orderCode, placeServerOrderVo.getCash(), null, placeServerOrderVo.getIp(), placeServerOrderVo.getOrderRamark());
//                if (result.getPackageValue() != null) {
//                    appletProductOrder.setPrepayId(JSON.toJSONString(result));
//                    appletProductOrderMapper.updateById(appletProductOrder);
//                }
//                else {
//                    appletProductOrder.setPayStatus(3);
//                    appletProductOrderMapper.updateById(appletProductOrder);
//                    return R.fail("下单失败");
//                }
//                placeOrderVO.setObject(result);
                //返回数据，前端调起支付
                PrepayWithRequestPaymentResponse payment = payment(orderCode, member.getOpenid(),placeServerOrderVo.getCash().multiply(new BigDecimal(100)));
                placeOrderVO.setObject(payment);
            }//余额支付
            else if (placeServerOrderVo.getPayChannel() == 2) {
                if (placeServerOrderVo.getCash().compareTo(member.getCoupons()) <= 0) {
                    member.setCoupons(member.getCoupons().subtract(placeServerOrderVo.getCash()));//使用的消费金支付
                } else {
                    member.setCoupons(new BigDecimal(0));//消费金全部使用
                    member.setBalance(member.getBalance().subtract(placeServerOrderVo.getCash().subtract(member.getCoupons())));//余额减去不够付的付款金额
                }
                appletProductOrder.setPayTime(new Date());
                appletProductOrder.setPayStatus(2);
                memberService.updateById(member);
                appletProductOrderMapper.updateById(appletProductOrder);
                appletProductOrder.setCodeUrl(qRCodeUrl(appletProductOrder.getOrderCode()));
                placeOrderVO.setObject(orderCode);
            }
//            return insert>0?R.success():R.fail("添加订单失败");
        }
        else {
            return R.fail("下单失败!!!");
        }
        return R.success(placeOrderVO);
    }

    public String next(String prefix, int len) {
        if (len < 15) {
            throw new BizException("入参错误");
        }
        RedisAtomicLong redisAtomicLong = new RedisAtomicLong(SERIAL_KEY,
                j2CahceRedisConnectionFactory);
        String dateStr = LocalDateTime.now()
                .format(DateTimeFormatter.ofPattern(DatePattern.PURE_DATETIME_PATTERN));
        len = len - dateStr.length();
        redisAtomicLong.expire(60, TimeUnit.SECONDS);
        String serial = String.valueOf(redisAtomicLong.incrementAndGet());
        if (serial.length() > len) {
            redisAtomicLong = new RedisAtomicLong(SERIAL_KEY, j2CahceRedisConnectionFactory, 1);
            serial = String.valueOf(redisAtomicLong.incrementAndGet());
        }
        return prefix + dateStr + StrUtil.fillBefore(serial, '0', len);
    }


    @Override
    public R<Object> payOrder(Long mid, Integer orderId, String ip) {
        if (mid == null) {
            return R.fail("参数异常，无法支付");
        }
        AppletServerOrder order = appletServerOrderMapper.selectOne(new QueryWrapper<AppletServerOrder>().eq("id", orderId));
        if (order == null) {
            return R.fail("订单不存在");
        }
        if (order.getCosts() == null) {
            return R.fail("没有选择服务或服务方式，没办法计算订单金额!!!");
        }
        if (order.getPayStatus() != 1) {
            return R.fail("订单状态不正确，无法支付");
        }


        //生成核销用二维码
        order.setCodeUrl(qRCodeUrl(String.valueOf(order.getId())));

        AppletMember member = appletMemberMapper.selectOne(new QueryWrapper<AppletMember>().eq("id", mid));
        Integer payChannel = order.getPayChannel();
        if (payChannel == 1) {
            //微信支付
            WxPayAppOrderResult result = wxPay2(order.getOrderCode(), order.getCosts(), member.getOpenid(), ip, null, payService);
            if (result.getPackageValue() != null) {
                order.setPrepayId(JSON.toJSONString(result));
                order.setPayStatus(2);//修改状态为已支付
                order.setServerStatus(2);//修改订单状态为待确认（等待商家/理疗车确认该订单信息）
//                baseMapper.updateById(order);
                appletServerOrderMapper.updateById(order);
            } else {
                return R.fail("支付失败");
            }
            return R.success(result);
        } else {
            //余额支付
            BigDecimal balance = member.getBalance();//用户的余额
            if (balance.compareTo(order.getCosts()) < 0) {//余额小于费用
                return R.fail("支付失败,余额不足");
            }
            member.setBalance(balance.subtract(order.getCosts()));//余额减去费用
            appletMemberMapper.updateById(member);

            order.setPayStatus(2);//修改状态为已支付
            //order.setServerStatus(2);//修改订单状态为待确认（等待商家/理疗车确认该订单信息）
            appletServerOrderMapper.updateById(order);

        }

        return R.success("支付成功");
    }

    @Override
    public R setServerStoreOrVehicles(SetServerStoreOrVehiclesVo setServerStoreOrVehiclesVo) {
        QueryWrapper<AppletServerOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", setServerStoreOrVehiclesVo.getServerOrderId());
        AppletServerOrder order = appletServerOrderMapper.selectOne(queryWrapper);

        AppletServerOrder serverOrder = new AppletServerOrder();
        if (setServerStoreOrVehiclesVo.getServerChannel() == null
                || (setServerStoreOrVehiclesVo.getServerChannel() != 0
                && setServerStoreOrVehiclesVo.getServerChannel() != 1)) {
            return R.fail("没有选择到店方式或传入的数据值错误!!!");
        }
        serverOrder.setServerChannel(setServerStoreOrVehiclesVo.getServerChannel());
        /*if (setServerStoreOrVehiclesVo.getBookingTime()==null){
            return R.fail("没有指定预约时间!!!");
        }*/
        if (serverOrder.getServerChannel() == 0) {
            //上门
            if (setServerStoreOrVehiclesVo.getVehiclesId() == null) {
                return R.fail("没有选择理疗车id!!!");
            }
            serverOrder.setVehiclesId(setServerStoreOrVehiclesVo.getVehiclesId());
            /*if (setServerStoreOrVehiclesVo.getAddressId() == null) {
                return R.fail("没有选择地址!!!");
            }*/
            serverOrder.setAddressId(setServerStoreOrVehiclesVo.getAddressId());

        }
        if (serverOrder.getServerChannel() == 1) {
            //到店
            if (setServerStoreOrVehiclesVo.getStoreId() == null) {
                return R.fail("没有选择店铺!!!");
            }
            serverOrder.setStoreId(setServerStoreOrVehiclesVo.getStoreId());

        }
        serverOrder.setId(order.getId());
        serverOrder.setServerStatus(2);//设置订单状态为待确认

        appletServerOrderMapper.updateById(serverOrder);

        return R.success();
    }

    @Override
    public R serverOrderUpdateStatus(OrderStatusVo orderStatusVo) {
        AppletServerOrder serverOrder = new AppletServerOrder();
        if (orderStatusVo.getOrderId() == null) {
            return R.fail("订单id不能为空!!!");
        }
        serverOrder.setId(orderStatusVo.getOrderId());
        if (orderStatusVo.getOrderStatus() == null) {
            return R.fail("订单状态不能为空");
        }
        serverOrder.setServerStatus(orderStatusVo.getOrderStatus());
        int i = appletServerOrderMapper.updateById(serverOrder);
        return i > 0 ? R.success() : R.fail("修改失败");
    }

    @Override
    public R productOrderUpdateStatus(OrderStatusVo orderStatusVo) {
        AppletProductOrder productOrder=new AppletProductOrder();
        if (orderStatusVo.getOrderId() == null) {
            return R.fail("订单id不能为空!!!");
        }
        productOrder.setId(orderStatusVo.getOrderId());
        if (orderStatusVo.getOrderStatus() == null) {
            return R.fail("订单状态不能为空");
        }
        productOrder.setProductStatus(orderStatusVo.getOrderStatus());
        int i = appletProductOrderMapper.updateById(productOrder);
        return i > 0 ? R.success() : R.fail("修改失败");
    }

    @Override
    public R ServerOrderSignatureConfirmation(ServerOrderSignatureConfirmationVo serverOrderSignatureConfirmationVo) {
        QueryWrapper<AppletServerOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", serverOrderSignatureConfirmationVo.getOrderId());
        AppletServerOrder serverOrder1 = appletServerOrderMapper.selectOne(queryWrapper);
        if (serverOrder1.getServerStatus() != 5) {
            return R.fail("服务订单未结束!!!");
        }

        AppletServerOrder serverOrder = new AppletServerOrder();
        serverOrder.setId(serverOrderSignatureConfirmationVo.getOrderId());
        serverOrder.setServerStatus(6);//修改状态为已签字
        serverOrder.setAutograph(serverOrderSignatureConfirmationVo.getAutograph());
        int i = appletServerOrderMapper.updateById(serverOrder);
        return i > 0 ? R.success() : R.fail("修改失败!!!");
    }

    @Override
    @Transactional
    public R serverOrderStart(String orderCode) {
        QueryWrapper<AppletServerOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_code", orderCode);
        AppletServerOrder serverOrder = appletServerOrderMapper.selectOne(queryWrapper);
        AppletProductOrder appletProductOrder = appletProductOrderMapper.selectOne(new QueryWrapper<AppletProductOrder>().eq("order_code", orderCode));
        if (appletProductOrder != null){
            appletProductOrder.setCodeUrl(null);
            appletProductOrderMapper.updateById(appletProductOrder);
        }
        AppletServerOrder appletServerOrder = appletServerOrderMapper.selectOne(new QueryWrapper<AppletServerOrder>().eq("order_code", orderCode));
        if (appletServerOrder!=null) {
            appletServerOrder.setCodeUrl(null);
            appletServerOrderMapper.updateById(appletServerOrder);
        }
        if(serverOrder!=null){
            if (serverOrder.getServerStatus() != 3) {
                return R.fail("服务订单未确认!!!");
            }

            Long mid = getMid();
            Store store = ceresStoreMapper.selectByMid(mid);
            PcVehicles pcVehicles = pcVehiclesMapper.selectByUserId(mid);

//        System.out.println("111111111111:::  "+serverOrder.getStoreId());
//        System.out.println("2:::  "+store.getId());
//        System.out.println("3333333=== " + !serverOrder.getStoreId().equals(store.getId()));

            if (store!=null && !serverOrder.getStoreId().equals(store.getId())){
                return R.fail("店铺错误，无法核销!!!");
            }
            if (pcVehicles!=null && !serverOrder.getVehiclesId().equals(pcVehicles.getId())){
                return R.fail("理疗车错误，无法核销!!!");
            }

            //添加提成信息
            appletCommissionService.addCommission(serverOrder.getMid(),serverOrder.getPaySum());


            if (serverOrder.getServerChannel() == 2) {
                //到店
                QueryWrapper<CeresStore> ceresStoreQueryWrapper = new QueryWrapper<>();
                ceresStoreQueryWrapper.eq("id", serverOrder.getStoreId());

                CeresStore ceresStore = ceresStoreMapper.selectOne(ceresStoreQueryWrapper);
                ceresStore.setOrderQuantity(ceresStore.getOrderQuantity() + 1);//订单数量+1
                ceresStoreMapper.updateById(ceresStore);
            }
            OrderStatusVo orderStatusVo = new OrderStatusVo();
            orderStatusVo.setOrderId(serverOrder.getId());
            orderStatusVo.setOrderStatus(4);


            AppletMember appletMember = appletMemberMapper.selectById(getMid());

            if (appletMemberMapper.selectById(getMid()).getId() != null) {
                if (serverOrder.getCutAmount()  != null){
                    appletMember.setBalance(appletMember.getBalance().subtract(serverOrder.getCutAmount()));
                }
                appletMember.setBalance(appletMember.getBalance().add(serverOrder.getPaySum()));
                appletMemberMapper.updateById(appletMember);
            }

            return serverOrderUpdateStatus(orderStatusVo);
        }else {
            if (appletProductOrder.getProductStatus() == 3) {
                return R.fail("产品订单已收货!!!");
            }

            Long mid = getMid();
            Store store = ceresStoreMapper.selectByMid(mid);
            PcVehicles pcVehicles = pcVehiclesMapper.selectByUserId(mid);

            if (store!=null && !appletProductOrder.getStoreId().equals(store.getId())){
                return R.fail("店铺错误，无法核销!!!");
            }
            if (pcVehicles!=null && !appletProductOrder.getVehiclesId().equals(pcVehicles.getId())){
                return R.fail("理疗车错误，无法核销!!!");
            }

            //添加提成信息
            appletCommissionService.addCommission(appletProductOrder.getMid(),appletProductOrder.getPaySum());
            /*if (serverOrder.getServerChannel() == 2) {
                //到店
                QueryWrapper<CeresStore> ceresStoreQueryWrapper = new QueryWrapper<>();
                ceresStoreQueryWrapper.eq("id", serverOrder.getStoreId());

                CeresStore ceresStore = ceresStoreMapper.selectOne(ceresStoreQueryWrapper);
                ceresStore.setOrderQuantity(ceresStore.getOrderQuantity() + 1);//订单数量+1
                ceresStoreMapper.updateById(ceresStore);
            }*/
            OrderStatusVo orderStatusVo = new OrderStatusVo();
            orderStatusVo.setOrderId(appletProductOrder.getId());
            orderStatusVo.setOrderStatus(3);
            return productOrderUpdateStatus(orderStatusVo);
        }

    }

    @Override
    public R serverOrderConfirm(OrderStatusVo orderStatusVo) {
        QueryWrapper<AppletServerOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", orderStatusVo.getOrderId());
        AppletServerOrder serverOrder = appletServerOrderMapper.selectOne(queryWrapper);
        if (serverOrder.getServerStatus() != 2) {
            return R.fail("服务方式未选择!!!");
        }
        if (serverOrder.getPayStatus() != 2) {
            return R.fail("订单未支付!!!");
        }
        return serverOrderUpdateStatus(orderStatusVo);
    }

    @Override
    public R serverOrderComplete(OrderStatusVo orderStatusVo) {
        QueryWrapper<AppletServerOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", orderStatusVo.getOrderId());
        AppletServerOrder serverOrder = appletServerOrderMapper.selectOne(queryWrapper);
        if (serverOrder.getServerStatus() != 4) {
            return R.fail("服务未开始!!!");
        }
        AppletMember appletMember = new AppletMember();
        if (serverOrder.getStoreId() != null) {
            CeresStore ceresStore = ceresStoreMapper.selectById(serverOrder.getStoreId());
            if (ceresStore!=null) {
                appletMember = appletMemberMapper.selectById(ceresStore.getMid());
            }
        }else{
            PcVehicles pcVehicles = pcVehiclesMapper.selectById(serverOrder.getVehiclesId());
            if (pcVehicles != null) {
                appletMember = appletMemberMapper.selectById(pcVehicles.getUserId());
            }
        }
        appletMember.setBalance(appletMember.getBalance().add(serverOrder.getPaySum()));
        appletMemberMapper.updateById(appletMember);
        return serverOrderUpdateStatus(orderStatusVo);
    }

    @Override
    public R cancelPay(OrderStatusVo orderStatusVo) {
        QueryWrapper<AppletServerOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", orderStatusVo.getOrderId());
        AppletServerOrder serverOrder = appletServerOrderMapper.selectOne(queryWrapper);
        if (serverOrder == null) {
            return R.fail("没有找到该订单!!!");
        }
        if (serverOrder.getPayStatus() == 2) {
            return R.fail("该订单已支付，无法取消!!!");
        }
        if (serverOrder.getPayStatus() == 3) {
            return R.fail("该订单已取消，不能重复取消!!!");
        }
        AppletServerOrder serverOrder1 = new AppletServerOrder();
        serverOrder1.setId(orderStatusVo.getOrderId());
        serverOrder1.setPayStatus(3);//设置支付状态为已取消
        int i = appletServerOrderMapper.updateById(serverOrder1);
        return i > 0 ? R.success() : R.fail("取消失败!!!");
    }

    @Override
    public R findMyServer(PageDate pageDate) {
        Page<MyServerOrderListVo> page = new Page<>(pageDate.getPageNum(), pageDate.getPageSize());
        Page<MyServerOrderListVo> pageList = appletServerOrderMapper.selectByMid(page, getMid());
        return R.success(pageList);
    }

    @Override
    public AppletServerOrder selectByOrderCode(String orderCode) {
        QueryWrapper<AppletServerOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_code",orderCode);
        AppletServerOrder appletServerOrder = appletServerOrderMapper.selectOne(queryWrapper);
        return appletServerOrder;
    }

    @Override
    public R examine(HeXiaoDto dto) {
        //小程序服务订单核销
        AppletProductOrder appletProductOrder = appletProductOrderService.selectByOrderCode(dto.getOrderCode());
        AppletServerOrder appletServerOrder = this.selectByOrderCode(dto.getOrderCode());
        if (appletProductOrder!=null){
            //产品订单处理
            return appletProductOrderService.confirmReceipt(appletProductOrder.getId());
        }else if(appletServerOrder!=null){
//            //服务订单处理
//
//            OrderStatusVo orderStatusVo = new OrderStatusVo();
//            orderStatusVo.setOrderId(appletServerOrder.getId());
//            orderStatusVo.setOrderStatus(4);//调整服务订单的状态为进行中
//            

            return this.serverOrderStart(dto.getOrderCode());
        }
        return R.fail("核销失败");
    }

    @Override
    public R findServerOrderList(PageDate pageDate) {
        Page<ServerOrderListVo> page = new Page<>(pageDate.getPageNum(), pageDate.getPageSize());
        Page<ServerOrderListVo> pageList = appletServerOrderMapper.selectServerByPageAndMid(page, null);
        return R.success(pageList);
    }

    private WxPayAppOrderResult wxPay2(String outTradeNo, BigDecimal sum, String openId, String ip, String orderInfo) {
        WxPayUnifiedOrderRequest request = new WxPayUnifiedOrderRequest();

        //商户订单号
        request.setOutTradeNo(outTradeNo);
        //微信用户ID
        request.setOpenid(openId);
        //内容
        request.setBody(outTradeNo);
        //总金额  单位：分
        request.setTotalFee(sum.multiply(new BigDecimal(100)).intValue());
        //终端IP
        request.setSpbillCreateIp(ip);
        request.setTradeType("APP");
        request.setAppid(appid);
        request.setNonceStr(secret);
        //埋点支付
        return payService.unifiedOrder(request);
    }

    public static WxPayAppOrderResult wxPay2(String outTradeNo, BigDecimal sum, String openId, String ip, String orderInfo, PayService payService) {
        WxPayUnifiedOrderRequest request = new WxPayUnifiedOrderRequest();

        //商户订单号
        request.setOutTradeNo(outTradeNo);
        //微信用户ID
        request.setOpenid(openId);
        //内容
        request.setBody(outTradeNo);
        //总金额  单位：分
        request.setTotalFee(sum.intValue());
        //终端IP
        request.setSpbillCreateIp(ip);
        //埋点支付
        return payService.unifiedOrder(request);
    }

    //生成二维码图片地址
    public String qRCodeUrl(String content) {
        String fileName = UUID.randomUUID().toString() + StrPool.DOT + "png";
        //日期文件夹
        String relativePath = Paths.get(LocalDate.now().format(DateTimeFormatter.ofPattern(DEFAULT_MONTH_FORMAT_SLASH))).toString();
        // web服务器存放的绝对路径
        String absolutePath = Paths.get(fileProperties.getStoragePath(), relativePath).toString();
        QcodeUtil.getQRCode(content, Paths.get(absolutePath, fileName).toString());
        String url = new StringBuilder(fileProperties.getUriPrefix())
                .append(relativePath)
                .append(StrPool.SLASH)
                .append(fileName)
                .toString();
        //替换掉windows环境的\路径
        url = StrUtil.replace(url, "\\\\", StrPool.SLASH);
        url = StrUtil.replace(url, "\\", StrPool.SLASH);
        return url;
    }

    public PrepayWithRequestPaymentResponse payment(String orderCode,String openId, BigDecimal cash){
        // 订单号
        String orderUuid = orderCode;
        //元转换为分
        Integer amountInteger = cash.intValue() * 100;
        //私钥文件路径（本地自己测试看自己的私钥文件存放路径）
//        String filePath ="E:\\liliao\\apiclient_key.pem";
        String filePath ="/opt/llc/cert/apiclient_key.pem";

        // 一个商户号只能初始化一个配置，否则会因为重复的下载任务报错
        if (config == null) {
            config =new RSAAutoCertificateConfig.Builder()
                    .merchantId("1666915143")
                    .privateKeyFromPath(filePath)
                    .merchantSerialNumber("140DEA0F5B3FC9FB0B158EE29CECB62F2307CA74")
                    .apiV3Key("A6fG7K6jL8VwQ5RmP1nZyB4dC3HqT0aS")
                    .build();
        }
        // 构建service
        if (service == null) {
            service = new JsapiServiceExtension.Builder().config(config).build();
        }

        //组装预约支付的实体
        PrepayRequest request = new PrepayRequest();
        //计算金额
        Amount amount =new Amount();
        amount.setTotal(cash.intValue());
        amount.setCurrency("CNY");
        request.setAmount(amount);
        String appid="wx31883f01947e7804";
        //公众号appId
        request.setAmount(amount);
        request.setAppid(appid);
//        request.setAmount(new PrepayRequest().getAmount());
//        request.getAmount().setTotal(1);
        request.setAmount(amount);

        //商户号
        request.setMchid("1666915143");
        //支付者信息
        Payer payer=new Payer();
        payer.setOpenid(openId);
        request.setPayer(payer);
        //描述
        request.setDescription("小程序支付");
        //微信回调地址，需要是https://开头的，必须外网可以正常访问
        request.setNotifyUrl("https://sanshitang1863.com/api/pay/notify/order");
        //订单号
        request.setOutTradeNo(orderUuid);

        // 加密
        PrepayWithRequestPaymentResponse payment = service.prepayWithRequestPayment(request);
        //默认加密类型为RSA
        payment.setSignType("MD5");
        System.out.println(payment);
        return payment;
    }
}
